package com.pingan.springboot_es_api.exception;


import com.pingan.springboot_es_api.domain.RestResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;


@ControllerAdvice(basePackages = "com.kay.springboot_es_api.controller")
public class GlobalExceptionHandler {
    private static final String logExceptionFormat = "Capture Exception By GlobalExceptionHandler: Code: %s Detail: %s";
    private static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public RestResult<String> errorHandler(HttpServletRequest request, Exception ex)throws Exception {
        log.error("捕获到Exception异常",ex);
        RestResult<String> r = new RestResult<>();
        r.setMsg(ex.getMessage());
        if (ex instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            r.setCode(404);
        } else {
            r.setCode(500);
        }
        r.setData("");
        r.setSuccess(false);
        r.setUrl(request.getRequestURI());

        r.setCurrentTime(new Timestamp(new Date().getTime()));

        return r;
    }

    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public RestResult<String> jsonErrorHandler(HttpServletRequest request, MyException e) throws Exception {
        log.error("捕获到MyException异常",e);
        RestResult<String> r = new RestResult<>();
        r.setCode(500);
        r.setMsg(e.getMessage());
        r.setSuccess(false);
        r.setData("");
        r.setUrl(request.getRequestURL().toString());
        r.setCurrentTime(new Timestamp(new Date().getTime()));
        return r;
    }
}
